<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<view class="nav-tabs">
			<view 
				class="nav-tab" 
				:class="{ active: currentTab === 0 }"
				@click="switchTab(0)"
			>
				<text>笔记</text>
				<text class="item-count">{{ notes.filter(item => item.type === 'note').length }} 条</text>
			</view>
			<view 
				class="nav-tab" 
				:class="{ active: currentTab === 1 }"
				@click="switchTab(1)"
			>
				<text>待办</text>
				<text class="item-count">{{ notes.filter(item => item.type === 'todo').length }} 条</text>
			</view>
		</view>
		
		<!-- 左右滑动切换区域 -->
		<view class="swiper-container">
			<swiper 
				:current="currentTab" 
				@change="tabChange" 
				class="swiper-box"
				:duration="300"
			>
				<!-- 笔记页面 -->
				<swiper-item class="swiper-item">
					<scroll-view 
						scroll-y 
						class="scroll-area"
						:refresher-enabled="true"
						:refresher-triggered="refreshing"
						@refresherrefresh="onRefresh"
					>
						<view 
							v-for="(item, index) in notes.filter(note => note.type === 'note')" 
							:key="index" 
							class="item-card"
							@click="viewDetail(item)"
						>
							<view class="item-header">
								<text class="item-title">{{ item.title }}</text>
								<text v-if="item.tag" class="item-tag">{{ item.tag }}</text>
							</view>
							<view class="item-content">
								<text class="item-text">{{ getPlainText(item.content) }}</text>
							</view>
							<view class="item-meta">
								<text class="item-time">{{ item.time }}</text>
								<view class="item-actions">
									<button @click.stop="editItem(item, index)" class="action-btn edit-btn">编辑</button>
									<button @click.stop="deleteItem(item, index)" class="action-btn delete-btn">删除</button>
								</view>
							</view>
						</view>
						<view v-if="notes.filter(note => note.type === 'note').length === 0" class="empty-tip">
							<text>暂无笔记，点击右下角添加</text>
						</view>
					</scroll-view>
				</swiper-item>
				
				<!-- 待办页面 -->
				<swiper-item class="swiper-item">
					<scroll-view 
						scroll-y 
						class="scroll-area"
						:refresher-enabled="true"
						:refresher-triggered="refreshing"
						@refresherrefresh="onRefresh"
					>
						<view 
							v-for="(item, index) in notes.filter(note => note.type === 'todo')" 
							:key="index" 
							class="item-card"
							:class="{'completed': item.completed}"
							@click="viewDetail(item)"
						>
							<view class="item-header">
								<text class="item-title">{{ item.title }}</text>
								<text v-if="item.tag" class="item-tag">{{ item.tag }}</text>
							</view>
							<view class="item-content">
								<text class="item-text">{{ getPlainText(item.content) }}</text>
							</view>
							<view class="item-meta">
								<text class="item-time">{{ item.time }}</text>
								<view class="item-actions">
									<button @click.stop="editItem(item, index)" class="action-btn edit-btn">编辑</button>
									<button @click.stop="deleteItem(item, index)" class="action-btn delete-btn">删除</button>
								</view>
							</view>
						</view>
						<view v-if="notes.filter(note => note.type === 'todo').length === 0" class="empty-tip">
							<text>暂无待办事项，点击右下角添加</text>
						</view>
					</scroll-view>
				</swiper-item>
			</swiper>
		</view>
		
		<!-- 添加按钮 -->
		<view class="add-btn" @click="showAddPopup">
			<text class="add-icon">+</text>
		</view>
		
		<!-- 编辑弹窗 -->
		<uni-popup ref="editorPopup" type="bottom" bg="none" :animation="false" disable-animation>
			<view class="editor-popup">
				<view class="popup-header">
					<text class="popup-title">{{ editingIndex === -1 ? '添加' : '编辑' }}{{ currentType === 'note' ? '笔记' : '待办' }}</text>
					<text class="close-btn" @click="closePopup">×</text>
				</view>
				
				<view class="editor-form">
					<input 
						v-model="newNoteTitle" 
						placeholder="请输入标题..." 
						class="note-title-input"
						:focus="titleFocus"
						@focus="onTitleFocus"
					/>
					<textarea 
						v-model="newNoteContent" 
						placeholder="请输入内容..." 
						class="note-content-input"
						:focus="contentFocus"
						@focus="onContentFocus"
					/>
					<input 
						v-model="newNoteTag" 
						placeholder="请输入标签(可选)..." 
						class="note-tag-input"
						:focus="tagFocus"
						@focus="onTagFocus"
					/>
					
					<view class="priority-section" v-if="currentType === 'todo'">
						<text class="priority-label">优先级:</text>
						<radio-group @change="changePriority" class="priority-group">
							<label class="priority-item">
								<radio value="low" :checked="newNotePriority === 'low'" />
								<text>低</text>
							</label>
							<label class="priority-item">
								<radio value="medium" :checked="newNotePriority === 'medium'" />
								<text>中</text>
							</label>
							<label class="priority-item">
								<radio value="high" :checked="newNotePriority === 'high'" />
								<text>高</text>
							</label>
						</radio-group>
					</view>
					
					<view class="button-group">
						<button @click="saveItem" class="save-btn" :disabled="!newNoteTitle.trim() || !newNoteContent.trim()">
							{{ editingIndex === -1 ? '添加' : '更新' }}
						</button>
						<button @click="closePopup" class="cancel-btn">
							取消
						</button>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import uniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue'
	import config from '@/config/api.js'
	
	export default {
		components: {
			uniPopup
		},
		data() {
			return {
				currentTab: 0, // 0: 笔记, 1: 待办
				currentType: 'note', // 当前编辑类型
				newNoteTitle: '',
				newNoteContent: '',
				newNoteTag: '',
				newNotePriority: 'medium',
				notes: [],
				editingIndex: -1,
				editingNoteId: null,
				userId: '',
				refreshing: false, // 下拉刷新状态
				// 添加用于控制输入框焦点的属性
				titleFocus: false,
				contentFocus: false,
				tagFocus: false
			}
		},
		onLoad() {
			// 获取用户ID
			const getOpenId = () => {
				const userInfo = uni.getStorageSync('userInfo') 
				this.userId = userInfo.id || 'anonymous';
				// 获取到用户ID后加载数据
				this.loadNotes();
				// 注释掉自动同步，避免重复上传数据
				// this.syncNotes();
			};
			getOpenId();
		},
		// 下拉刷新
		onPullDownRefresh() {
			this.loadNotes().then(() => {
				uni.stopPullDownRefresh();
			}).catch(() => {
				uni.stopPullDownRefresh();
			});
		},
		methods: {
			// 切换标签页
			switchTab(tab) {
				this.currentTab = tab;
				this.currentType = tab === 0 ? 'note' : 'todo';
			},
			
			// 滑动切换页面
			tabChange(e) {
				this.currentTab = e.detail.current;
				this.currentType = this.currentTab === 0 ? 'note' : 'todo';
			},
			
			// 下拉刷新
			async onRefresh() {
				this.refreshing = true;
				try {
					await this.loadNotes();
					uni.showToast({
						title: '刷新成功',
						icon: 'success',
						duration: 1000
					});
				} catch (e) {
					console.error('刷新失败', e);
					uni.showToast({
						title: '刷新失败',
						icon: 'none',
						duration: 1000
					});
				} finally {
					this.refreshing = false;
				}
			},
			
			// 显示添加弹窗
			showAddPopup() {
				this.editingIndex = -1;
				this.editingNoteId = null;
				this.newNoteTitle = '';
				this.newNoteContent = '';
				this.newNoteTag = '';
				this.newNotePriority = 'medium';
				this.$refs.editorPopup.open();
				// 延迟设置焦点，确保弹窗完全打开
				setTimeout(() => {
					this.titleFocus = true;
				}, 100);
			},
			
			// 关闭弹窗
			closePopup() {
				this.$refs.editorPopup.close();
				// 重置焦点状态
				this.titleFocus = false;
				this.contentFocus = false;
				this.tagFocus = false;
				// 延迟重置表单数据，确保动画完成后再清理
				setTimeout(() => {
					this.newNoteTitle = '';
					this.newNoteContent = '';
					this.newNoteTag = '';
					this.newNotePriority = 'medium';
				}, 300);
			},
			
			// 标题输入框获得焦点时的处理
			onTitleFocus() {
				this.titleFocus = true;
				// 如果输入框为空，光标会自然定位在提示文本前面
			},
			
			// 内容输入框获得焦点时的处理
			onContentFocus() {
				this.contentFocus = true;
				// 如果输入框为空，光标会自然定位在提示文本前面
			},
			
			// 标签输入框获得焦点时的处理
			onTagFocus() {
				this.tagFocus = true;
				// 如果输入框为空，光标会自然定位在提示文本前面
			},
			
			// 手动设置标题输入框焦点
			focusTitle() {
				this.titleFocus = true;
				this.contentFocus = false;
				this.tagFocus = false;
			},
			
			// 手动设置内容输入框焦点
			focusContent() {
				this.titleFocus = false;
				this.contentFocus = true;
				this.tagFocus = false;
			},
			
			// 手动设置标签输入框焦点
			focusTag() {
				this.titleFocus = false;
				this.contentFocus = false;
				this.tagFocus = true;
			},
			
			// 保存项目
			async saveItem() {
				if (!this.newNoteTitle.trim() || !this.newNoteContent.trim()) return;
				
				const currentTime = this.getCurrentTime();
				const userId = this.userId;
				if (!userId) {
					uni.showToast({ title: '用户ID不能为空', icon: 'none' });
					return;
				}
				
				const noteData = {
					title: this.newNoteTitle.trim(),
					content: this.newNoteContent.trim(),
					tag: this.newNoteTag.trim(),
					type: this.currentType,
					create_time: currentTime,
					user_id: userId
				};
				
				// 如果是待办事项，添加优先级
				if (this.currentType === 'todo') {
					noteData.priority = this.newNotePriority;
				}
				
				if (this.editingIndex === -1) {
					// 添加新项目
					try {
						const res = await uni.request({
							url: config.baseUrl + config.api.notes,
							method: 'POST',
							data: noteData
						});
						
						if (res.statusCode === 200 || res.statusCode === 201) {
							uni.showToast({ title: '提交成功', icon: 'success' });
							// 从响应中获取数据库ID并添加到本地列表
							const noteWithId = {
								id: res.data.id || Date.now(),
								...noteData
							};
							this.notes.unshift(noteWithId);
							this.closePopup();
							this.saveNotes();
						} else {
							uni.showToast({ title: '提交失败', icon: 'none' });
						}
					} catch (e) {
						uni.showToast({ title: '网络错误', icon: 'none' });
					}
				} else {
					// 更新项目
					const itemToUpdate = this.notes[this.editingIndex];
					noteData.updated = currentTime;
					
					try {
						const res = await uni.request({
							url: config.baseUrl + config.api.notes + '/' + itemToUpdate.id,
							method: 'PUT',
							data: {
								...itemToUpdate,
								...noteData
							}
						});
						
						if (res.statusCode === 200 || res.statusCode === 201) {
							uni.showToast({ title: '更新成功', icon: 'success' });
							// 更新本地数据
							this.$set(this.notes, this.editingIndex, {
								...itemToUpdate,
								...noteData
							});
							this.closePopup();
							this.saveNotes();
						} else {
							uni.showToast({ title: '更新失败', icon: 'none' });
						}
					} catch (e) {
						uni.showToast({ title: '网络错误', icon: 'none' });
					}
				}
			},
			
			// 编辑项目
			editItem(item, index) {
				this.editingIndex = index;
				this.editingNoteId = item.id;
				this.currentType = item.type;
				this.newNoteTitle = item.title || '';
				this.newNoteContent = item.content || '';
				this.newNoteTag = item.tag || '';
				this.newNotePriority = item.priority || 'medium';
				this.$refs.editorPopup.open();
				// 延迟设置焦点，确保弹窗完全打开
				setTimeout(() => {
					this.titleFocus = true;
				}, 100);
			},
			
			// 删除项目
			async deleteItem(item, index) {
				uni.showModal({
					title: '提示',
					content: `确定要删除这条${item.type === 'note' ? '笔记' : '待办'}吗？`,
					success: async (res) => {
						if (res.confirm) {
							// 如果项目有ID，则从服务器删除
							if (item.id) {
								try {
									const res = await uni.request({
										url: config.baseUrl + config.api.notes + '/' + item.id,
										method: 'DELETE'
									});
									
									if (res.statusCode === 200 || res.statusCode === 204) {
										uni.showToast({ title: '删除成功', icon: 'success' });
										this.notes.splice(index, 1);
										this.saveNotes();
									} else {
										uni.showToast({ title: '删除失败', icon: 'none' });
									}
								} catch (e) {
									uni.showToast({ title: '网络错误', icon: 'none' });
								}
							} else {
								// 如果没有ID，则只从本地删除
								this.notes.splice(index, 1);
								this.saveNotes();
							}
						}
					}
				});
			},
			
			// 查看详情
			viewDetail(item) {
				// 这里可以跳转到详情页面，或者在弹窗中显示详细内容
				uni.showToast({
					title: '点击查看详情',
					icon: 'none'
				});
			},
			
			// 改变优先级
			changePriority(e) {
				this.newNotePriority = e.detail.value;
			},
			
			// 获取当前时间
			getCurrentTime() {
				const now = new Date();
				const year = now.getFullYear();
				const month = String(now.getMonth() + 1).padStart(2, '0');
				const day = String(now.getDate()).padStart(2, '0');
				const hours = String(now.getHours()).padStart(2, '0');
				const minutes = String(now.getMinutes()).padStart(2, '0');
				return `${year}-${month}-${day} ${hours}:${minutes}`;
			},
			
			// 从服务器加载
			async loadNotes() {
				uni.showLoading({ title: '加载中...' });
				try {
					const res = await uni.request({
						url: config.baseUrl + config.api.notes,
						method: 'GET',
						data: {
							user_id: this.userId
						}
					});
					
					uni.hideLoading();
					console.log(res.data.data.notes);
					
					if (res.data.code === 200) {
						// 成功获取数据
						this.notes = res.data.data.notes;
						uni.showToast({ title: '加载成功', icon: 'success' });
					} else {
						// 如果服务器获取失败，尝试从本地存储加载
						const localNotes = uni.getStorageSync('notes');
						if (localNotes) {
							this.notes = localNotes;
							uni.showToast({ title: '已加载本地数据', icon: 'none' });
						} else {
							this.notes = [];
						}
					}
				} catch (e) {
					uni.hideLoading();
					console.error('从服务器加载失败', e);
					// 如果网络错误，尝试从本地存储加载
					const localNotes = uni.getStorageSync('notes');
					if (localNotes) {
						this.notes = localNotes;
						uni.showToast({ title: '已加载本地数据', icon: 'none' });
					} else {
						this.notes = [];
					}
				}
			},

			// 保存到本地存储
			saveNotes() {
				try {
					uni.setStorageSync('notes', this.notes);
				} catch (e) {
					console.error('保存失败', e);
				}
			},
			
			// 同步到服务器
			async syncNotes() {
				try {
					// 获取本地存储的数据
					const localNotes = uni.getStorageSync('notes');
					if (localNotes && localNotes.length > 0) {
						let syncCount = 0;
						// 批量上传本地数据到服务器
						for (const note of localNotes) {
							// 检查是否已存在于服务器
							const exists = this.notes.some(n => n.id === note.id);
							if (!exists) {
								// 不存在则上传
								const res = await uni.request({
									url: config.baseUrl + config.api.notes,
									method: 'POST',
									data: {
										...note,
										user_id: this.userId // 确保使用当前用户ID
									}
								});
								
								if (res.statusCode === 200 || res.statusCode === 201) {
									syncCount++;
									// 更新本地数据的ID（如果服务器返回了新ID）
									if (res.data && res.data.id) {
										note.id = res.data.id;
									}
								}
							}
						}
						
						if (syncCount > 0) {
							// 更新本地存储
							uni.setStorageSync('notes', localNotes);
							uni.showToast({ title: `同步了${syncCount}条数据`, icon: 'success' });
						}
					}
				} catch (e) {
					console.error('同步失败', e);
					uni.showToast({ title: '数据同步失败', icon: 'none' });
				}
			},

			// 将Markdown内容转换为纯文本
			getPlainText(markdown) {
				if (!markdown) return '';
				// 移除常见的Markdown标记
				return markdown
					.replace(/#+\s/g, '') // 标题
					.replace(/\*\*(.*?)\*\*/g, '$1') // 加粗
					.replace(/\*(.*?)\*/g, '$1') // 斜体
					.replace(/~~(.*?)~~/g, '$1') // 删除线
					.replace(/`{1,2}([^`]+)`{1,2}/g, '$1') // 代码
					.replace(/!\[.*?\]\(.*?\)/g, '[图片]') // 图片
					.replace(/\[.*?\]\(.*?\)/g, '$1') // 链接
					.replace(/>\s/g, '') // 引用
					.replace(/- \[ \]/g, '[ ]') // 未完成任务
					.replace(/- \[x\]/g, '[x]') // 已完成任务
					.replace(/- /g, '') // 列表
					.replace(/\n/g, ' ') // 换行符
					.trim()
					.substring(0, 100) + (markdown.length > 100 ? '...' : '');
			}
		}
	}
</script>

<style scoped>
	.container {
		background-color: #f8f8f8;
		min-height: 100vh;
	}
	
	.nav-tabs {
		display: flex;
		flex-direction: row;
		background-color: white;
		border-bottom: 1rpx solid #eee;
	}
	
	.nav-tab {
		flex: 1;
		text-align: center;
		padding: 20rpx 0;
		font-size: 32rpx;
		color: #666;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
	
	.nav-tab.active {
		color: #f0ad4e;
		border-bottom: 4rpx solid #f0ad4e;
	}
	
	.item-count {
		font-size: 24rpx;
		color: #999;
		margin-top: 5rpx;
	}
	
	.swiper-container {
		flex: 1;
	}
	
	.swiper-box {
		height: calc(100vh - 180rpx); /* 减去header和nav-tabs的高度 */
	}
	
	.swiper-item {
		height: 100%;
	}
	
	.scroll-area {
		height: 100%;
		padding: 30rpx;
		box-sizing: border-box;
	}
	
	.item-card {
		background: #fff;
		border-radius: 10rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
	}
	
	.item-card.completed {
		opacity: 0.7;
	}
	
	.item-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 10rpx;
	}
	
	.item-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		flex: 1;
	}
	
	.item-tag {
		font-size: 24rpx;
		color: #f0ad4e;
		background-color: #fff9f0;
		padding: 5rpx 15rpx;
		border-radius: 30rpx;
	}
	
	.item-content {
		margin-bottom: 20rpx;
	}
	
	.item-text {
		font-size: 28rpx;
		color: #666;
		line-height: 1.5;
	}
	
	.item-meta {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.item-time {
		font-size: 24rpx;
		color: #999;
	}
	
	.item-actions {
		display: flex;
	}
	
	.action-btn {
		font-size: 24rpx;
		padding: 10rpx 20rpx;
		margin-left: 20rpx;
		border-radius: 6rpx;
		height: auto;
		line-height: 1;
	}
	
	.edit-btn {
		background: #f0ad4e;
		color: white;
	}
	
	.delete-btn {
		background: #ccc;
		color: #666;
	}
	
	.empty-tip {
		text-align: center;
		padding: 100rpx 0;
		color: #999;
		font-size: 28rpx;
	}
	
	.add-btn {
		position: fixed;
		bottom: 40rpx;
		right: 40rpx;
		width: 100rpx;
		height: 100rpx;
		background: #f0ad4e;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
		box-shadow: 0 4rpx 20rpx rgba(240, 173, 78, 0.4);
		z-index: 999;
	}
	
	.add-icon {
		font-size: 60rpx;
		color: white;
		font-weight: bold;
	}
	
	.editor-popup {
		background: #fff;
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;
		padding: 20rpx;
		max-height: 90vh;
		overflow-y: auto;
		transform: translateZ(0);
		will-change: transform;
		/* 添加平滑的过渡效果 */
		transition: transform 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
	}
	
	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #eee;
		margin-bottom: 20rpx;
	}
	
	.popup-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}
	
	.close-btn {
		font-size: 40rpx;
		color: #999;
		padding: 10rpx;
	}
	
	.editor-form {
		padding: 0 20rpx;
	}
	
	.note-title-input, .note-tag-input {
		width: 100%;
		padding: 20rpx;
		border: 1rpx solid #ddd;
		border-radius: 10rpx;
		background: #fff;
		font-size: 28rpx;
		box-sizing: border-box;
		margin-bottom: 20rpx;
		height: 80rpx;
		line-height: 80rpx;
		/* 确保提示文本在光标前面 */
		caret-color: #333;
	}
	
	.note-content-input {
		width: 100%;
		height: 300rpx;
		padding: 20rpx;
		border: 1rpx solid #ddd;
		border-radius: 10rpx;
		background: #fff;
		font-size: 28rpx;
		box-sizing: border-box;
		margin-bottom: 20rpx;
		/* 确保提示文本在光标前面 */
		caret-color: #333;
	}
	
	.priority-section {
		margin-bottom: 20rpx;
	}
	
	.priority-label {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 10rpx;
		display: block;
	}
	
	.priority-group {
		display: flex;
		flex-direction: row;
	}
	
	.priority-item {
		margin-right: 30rpx;
		display: flex;
		align-items: center;
	}
	
	.priority-item radio {
		margin-right: 10rpx;
	}
	
	.button-group {
		display: flex;
		flex-direction: row;
		gap: 20rpx;
		margin-top: 20rpx;
	}
	
	.save-btn {
		flex: 1;
		background: #f0ad4e;
		color: white;
		border: none;
		border-radius: 10rpx;
		font-size: 32rpx;
		height: 80rpx;
	}
	
	.cancel-btn {
		flex: 1;
		background: #ccc;
		color: #666;
		border: none;
		border-radius: 10rpx;
		font-size: 32rpx;
		height: 80rpx;
	}
	
	.save-btn[disabled] {
		background: #ccc;
	}
</style>